package cool.mtc.security.handler.auth.jwt;

import cool.mtc.security.auth.jwt.JwtAuthToken;
import cool.mtc.security.handler.auth.AuthSuccessHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 明河
 */
@Component
public class JwtAuthSuccessHandler extends AuthSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);

        JwtAuthToken authToken = (JwtAuthToken) authentication;
        if (authToken.getForm().isExpired()) {
            super.setTokenToResponseHeader(authToken.getForm().getToken());
        }

        super.publishAuthSuccessEvent(request, authToken.getForm(), authToken);
    }
}
